import { URL_COUNTDOWN } from "@/comm/api";
import { post } from "@/comm/request";
import { Notify } from "@/components/y-notify/script";
import { Ref, ref } from "vue";
type RES = {
    code: number;
    info: string;
    data: number;
}
type callFn = () => void;

class ActiveTime {
    private inte: any = 0;
    private dateNum = { d: 0, h: 0, m: 0, s: 0 };
    d: Ref<string> = ref('00');
    h: Ref<string> = ref('00');
    m: Ref<string> = ref('00');
    s: Ref<string> = ref('00');
    currTime=0
    constructor(private endtime: number, private callfn: callFn = () => { }) { }
    start() {
        let time = 0;
        this.currTime = this.endtime - new Date().getTime()
        if (this.endtime - new Date().getTime() > 0) {
            this.inte = setInterval(() => {
                time = this.endtime - new Date().getTime();
                this.dateNum.d = parseInt(String(time / 1000 / 60 / 60 / 24));
                this.dateNum.h = parseInt(String(time / 1000 / 60 / 60 % 24));
                this.dateNum.m = parseInt(String(time / 1000 / 60 % 60));
                this.dateNum.s = parseInt(String(time / 1000 % 60));

                // 补'0'
                this.d.value = String(this.dateNum.d < 10 ? String(0).concat(String(this.dateNum.d)) : this.dateNum.d);
                this.h.value = String(this.dateNum.h < 10 ? String(0).concat(String(this.dateNum.h)) : this.dateNum.h);
                this.m.value = String(this.dateNum.m < 10 ? String(0).concat(String(this.dateNum.m)) : this.dateNum.m);
                this.s.value = String(this.dateNum.s < 10 ? String(0).concat(String(this.dateNum.s)) : this.dateNum.s);
                // console.log('yzt计时器', Object.values(toRaw(this.dateStr)).join(':'));
                if (time < 0) {
                    this.close();
                    this.callfn();
                }
            }, 1000);
        } else {
            this.callfn();
        }
        return this;
    }
    close() {
        clearInterval(this.inte);
    }
}

const active = {
    timeData: ref<ActiveTime>(),
    init: async function (callfun: callFn) {
        const res: RES = await post(URL_COUNTDOWN);
        if (res.code === 200) {

            // console.log('yzt活动倒计时', res);
            this.timeData.value = new ActiveTime(res.data, callfun).start();
        } else {
            Notify.alert('time 404!', 'warning');
        }
    }
}

export { ActiveTime, active };